package com.write.program.util;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;

/**
 *
 * @description FtpUtils
 * @date 2019/7/9
 **/
public class FtpUtils {

    private static String USERNAME;
    private static String PASSWORD;
    private static String HOST;

    public static void init(String userName, String password, String host) {
        FtpUtils.USERNAME = userName;
        FtpUtils.PASSWORD = password;
        FtpUtils.HOST = host;
    }

    public static FTPClient getFtpClient() throws IOException {
        FTPClient ftp = new FTPClient();
        // 连接
        ftp.connect(HOST);// 连接FTP服务器
        ftp.login("abc", "123456");// 登陆FTP服务器
        ftp.setControlEncoding("UTF-8"); // 中文支持
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE); //二进制
        ftp.enterLocalPassiveMode();  // 被动模式
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            ftp.disconnect();
            throw new RuntimeException("未连接到FTP，用户名或密码错误。");
        }
        return ftp;
    }

    public static boolean download(String saveFilePath, String ftpFilePath,String fileName) {
        FTPClient ftpClient = null;
        OutputStream ios = null;
        boolean success = false;

        try {
            ftpClient = getFtpClient();

            //切换下载目录 2019/07/10/16/20190710165044_0_1002_1001.wav
            //切换下载目录 ftpFilePath/fileName
            ftpClient.changeWorkingDirectory(ftpFilePath);
            FTPFile[] ftpFiles = ftpClient.listFiles(fileName);
            if (ftpFiles.length > 0) {
                File  localFile = new File(saveFilePath + "/" + ftpFiles[0].getName());
                //先判断文件是否存在 如果存在就不重复下载
                if (!localFile.exists()) {
                    ios = new FileOutputStream(localFile);
                    success = ftpClient.retrieveFile(ftpFiles[0].getName(), ios);
                    ios.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ios != null) {
                    ios.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            close(ftpClient);
        }
        return success;
    }

    // 删除文件至FTP通用方法
    public static void deleteFileFtp(String filePath, String fileName) {
        FTPClient ftpClient = null;
        try {
            ftpClient = getFtpClient();
            ftpClient.cwd(filePath);// path为FTP服务器上保存上传文件的路径。
            ftpClient.deleteFile(fileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(ftpClient);
        }
    }

    //获取ftp某一文件（路径）下的文件名字,用于查看文件列表
    public void getFilesName() {
        StringBuffer buffer = new StringBuffer();
        FTPClient ftpClient = null;
        try {
            ftpClient = getFtpClient();
            //获取ftp里面，“Windows”文件夹里面的文件名字，存入数组中
            FTPFile[] files = ftpClient.listFiles("");
            //打印出ftp里面，“Windows”文件夹里面的文件名字
            for (int i = 0; i < files.length; i++) {
                System.out.println(files[i].getName());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            close(ftpClient);
        }
    }

    //下载文件的第二种方法，优化了传输速度
    public void getFile2() {
        FTPClient ftpClient = null;
        try {
            InputStream is = ftpClient.retrieveFileStream("zhuye.html");
            System.out.println("读取成功");
            FileOutputStream fos = new FileOutputStream(new File("D:/zhuye.html"));

            byte[] b = new byte[1024];
            int len = 0;
            while ((len = is.read(b)) != -1) {
                fos.write(b,0,len);
            }
            System.out.println("输出成功");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            close(ftpClient);
        }
    }

    public void putFile() {
        FTPClient ftpClient = null;
        try {
            OutputStream os = ftpClient.storeFileStream("D:/zhuye.html");
            FileInputStream fis = new FileInputStream(new File("D:/zhuye.html"));

            byte[] b = new byte[1024];
            int len = 0;
            while ((len = fis.read(b)) != -1) {
                System.out.println(b);
                System.out.println(len);
                os.write(b,0,len);
            }
        } catch (IOException e) {
            System.out.println("输出失败");
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("输出成功");
    }

    /**
     * ftpClient 连接断开
     *
     * @param client ftpClient 客户端
     */
    public static void close(FTPClient client) {
        if (client == null) {
            return;
        }
        try {
            client.logout();
            if (!client.isConnected())
                client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}